import os
import hashlib
import zipfile
import json
from common.consts import REPORT_PATH, DATA_PATH, BASE_PATH, CASE_PATH


def md5_code(passwd):
    md5 = hashlib.md5()
    md5.update(passwd.encode("utf-8"))
    return md5.hexdigest()


def trans_str(s):
    s = s.replace('":"', "=").replace('":', '=')
    return s


def zip_dir(startdir, zip_file):
    # 压缩文件夹
    # _zip_file = os.path.join(startdir, zip_file)
    _zip_file = zip_file
    if os.path.exists(_zip_file):
        # 先删除
        os.remove(_zip_file)
    z = zipfile.ZipFile(_zip_file, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(startdir):
        fpath = dir_path.replace(startdir, '')  # 不replace的话，就从根目录开始复制
        fpath = fpath and fpath + os.sep or ''
        for filename in file_names:
            z.write(os.path.join(dir_path, filename), fpath + filename)
    z.close()


def create_case():
    files = os.listdir(DATA_PATH)
    filenames = [file for file in files if file.startswith('test')]
    for i in filenames:
        yaml_name = i
        case_name = i.split('.')[0]
        module_name = '{}{}'.format(case_name, '.py')
        template = os.path.join(BASE_PATH, 'template.txt')
        with open(template, encoding='utf-8') as f:
            content = f.read() % (yaml_name, case_name)
        case = os.path.join(CASE_PATH, module_name)
        with open(case, 'w', encoding='utf-8') as f:
            f.write(content)


def create_case_json():
    files = os.listdir(DATA_PATH)
    filenames = [file for file in files if file.startswith('test')]
    for i in filenames:
        case_name = i.split('.')[0]
        module_name = '{}{}'.format(case_name, '.py')
        template = os.path.join(BASE_PATH, 'template1.txt')
        with open(template, encoding='utf-8') as f:
            content = f.read() % case_name
        case = os.path.join(CASE_PATH, module_name)
        with open(case, 'w', encoding='utf-8') as f:
            f.write(content)


def json_insert_data(url, method, file_path, new_file):
    """向json测试数据中插入指定参数并重组"""
    with open(file_path, 'r', encoding='utf-8') as f:
        original_data = json.load(f)

        # 转换数组
    transformed_data = []
    for index, item in enumerate(original_data, start=1):
        new_item = {
            "url": url,
            "method": method,
            "payload": {
                "title": "指定用户推送-标题",
                "body": "指定用户推送-内容",
                "extraMap": {
                    "imageUrl": "https://oss-community.dingstock.net/avatar/9185780858403378914.jpg",
                    "link": "https://app.dingstock.net/home/tab?id=usercenter",
                    "localize": True
                },
                "assignType": "userId",
                "assignId": item['userId']
            },
            "title": f"测试用户{item['userId']}推送"
        }
        transformed_data.append(new_item)

        # 将转换后的数据写入新的JSON文件
    with open(new_file, 'w', encoding='utf-8') as f:
        json.dump(transformed_data, f, ensure_ascii=False, indent=2)

# file = os.path.join(DATA_PATH, 'test_08_devine_comment.json')
#
# json_insert_data('/admin/user/u/assign','post',file_path=file, new_file=file)

# create_case_json()
